import {createVNode, render} from "vue";
import {instances} from "./instance.ts";
import MessageConstructor from "./message.vue"
import {createOptions} from "@/components/Message/message.ts";


function closeMessage(instance) {
    const idx = instances.indexOf(instance)
    if (idx === -1) return
    // 数组中移除该实例并执行销毁操作
    console.log("instance",instance)
    instances.splice(idx, 1)
    const {handler} = instance
    handler.close()
}

let seed = 0

function createMessage(
    {appendTo, ...options},
    context?
) {
    // 1. 生成 部分参数及方法
    const id = `message_${seed++}`

    const userOnClose = options.onClose
    const container = document.createElement('div')

    // 2. 生成需要传递下去的 props
    const props = {
        ...options,
        id,
        onClose: () => {
            userOnClose?.()
            closeMessage(instance)
        },
        onDestroy: () => {
            console.log("des")
            render(null, container)
        }
    }
    // 3. 生成虚拟 node 节点
    const vnode = createVNode(
        MessageConstructor,
        props
    )
    vnode.appContext = context || useMessage._context
    render(vnode, container)
    appendTo.appendChild(container.firstElementChild!)

    const vm = vnode.component!

    const handler  = {
        close: () => {
            vm.exposed!.visible.value = false
        },
    }

    // 5. 生成实例对象
    const instance = {
        id,
        vnode,
        vm,
        handler,
        props: (vnode.component as any).props,
    }

    return instance;
}


/**
 * 消息提示
 * @param options
 * @param context
 */
function useMessage(
    options: any,
    context?: any,
) {
    // 1. 对 options 进行解析处理
    const newOptions = createOptions(options)
    // 2. 判断

    // 3. 生成 instance 实例
    const instance = createMessage(newOptions, context);
    instances.push(instance)
    return instance.handler as any
}


export default useMessage
